package com.xmlt.ui.server;

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.loader.WebappLoader;
import org.apache.catalina.startup.Tomcat;

import com.xmlt.ui.editors.EditorsPlugin;

public class EmbeddedServer {
	private static Tomcat tomcat = null;
	private static int port = 9999;

	public static void start() throws LifecycleException {
		try {
			port = findFreePort();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		tomcat = new Tomcat();
		tomcat.setPort(port);

		File docBase = new File(EditorsPlugin.getResourceURL("site").substring(
				6));
		Context webAppContext = tomcat.addWebapp(null, "",
				docBase.getAbsolutePath());
		WebappLoader loader = new WebappLoader(
				EmbeddedServer.class.getClassLoader());
		webAppContext.setLoader(loader);

		tomcat.start();
	}

	public static String getRootUrl() {
		return "http://localhost:" + port + "/";
	}

	public static void stop() throws LifecycleException {
		if (tomcat != null) {
			tomcat.stop();
		}
	}

	private static int findFreePort() throws IOException {
		ServerSocket server = new ServerSocket(0);
		int port = server.getLocalPort();
		server.close();
		return port;
	}
}
